<template>
  <div ref="buttonRef" @click.stop="onClickOutside">
    <slot name="btn" />
  </div>
  <el-popover ref="popoverRef" :virtual-ref="buttonRef" trigger="click" :placement="placement" :width="width"
    virtual-triggering>
    <div class="list-b-8" ref="targetElement" :style="{
      padding: proxy.$size(padding, '8px'),
    }" @click.stop>
      <div :style="{
        height: proxy.$size(height, 'auto'),
        maxHeight: proxy.$size(maxHeight, '80vh'),
      }">
        <el-scrollbar>
          <slot :closeBtn="() => {
            closeBtn()
          }" />
        </el-scrollbar>
      </div>
    </div>
  </el-popover>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    title?: string; //菜单名称
    padding?: number | string; //宽度
    width?: number | string; //宽度
    height?: number | string; //固定高度
    maxHeight?: number | string; //最大高度
    placement?: string; //出现位置 top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end
    trigger?: string; //触发方式 click/focus/hover/contextmenu
    isHide?: boolean; //是否点击隐藏
    saveBtn?: Function; //是否点击隐藏
  }>(),
  {
    width: 600,
    placement: 'top',
  },
);
const buttonRef = ref()
const popoverRef = ref()
const targetElement = ref();
// 定义一个函数，在点击外部时触发
const handleClickOutside = (event: any) => {
  let _targetElement: any = targetElement.value
  if (_targetElement && !_targetElement.contains(event.target)) {
    // dataInfo.show = false
    // 在此处执行您想要的操作
  }
}
const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'clickBtn'): void;
}>();
const onClickOutside = () => {
  unref(popoverRef)?.popperRef?.delayHide?.()
  emit('clickBtn')
}
// 选择通话方式
const closeBtn = () => {
  //关闭起泡
  popoverRef.value.hide()
}
// 当组件挂载后，开始监听点击事件
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 当组件卸载前，移除事件监听以避免内存泄漏
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>
<style scoped>
.popover-btn {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
